package com.jh.user.service;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.TokenUtil;
import com.jh.user.business.PaymentProfitBusiness;
import com.jh.user.business.UserBalanceBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.*;
import com.jh.user.pojo.payment.PaymentProfit;
import com.jh.user.util.CommonsUtil;
import com.jh.user.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@EnableAutoConfiguration
public class UserBalanceService {

	private static final Logger LOG = LoggerFactory.getLogger(UserBalanceService.class);

	@Autowired
	private UserBalanceBusiness userBalBusiness;

	@Autowired
	private UserLoginRegisterBusiness userLoginRegisterBusiness;
	@Autowired
	Util util;
	@Autowired
	private PaymentProfitBusiness paymentProfitBusiness;

	/**获取用户当前账户信息*/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/user/account/query/{token}")
	public @ResponseBody Object queryUserAccount(HttpServletRequest request,
												 @PathVariable("token") String token){

		Map map = new HashMap();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.queryUserAccountByUserid(userId));
		return map;

	}
	/**获取用户当前账户信息*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/query/userId")
	public @ResponseBody Object queryUserAccountByUserId(HttpServletRequest request,
														 @RequestParam(value = "user_id") long userId){

		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.queryUserAccountByUserid(userId));
		return map;

	}

	/**获取用户当前账户信息*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/query/phone")
	public @ResponseBody Object queryUserAccountByPhone(HttpServletRequest request,
														@RequestParam(value = "phone") String phone,
														@RequestParam(value = "brand_id", defaultValue = "-1", required=false) long brandid
	){

		Map<String,Object> map = new HashMap<String,Object>();
		User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
		long userId = user.getId();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.queryUserAccountByUserid(userId));
		return map;

	}




	/**锁定当前用户的账户信息*/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/user/account/lock/{token}")
	public @ResponseBody Object lockUserAccount(HttpServletRequest request,
												@PathVariable("token") String token){


		Map map = new HashMap();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}


		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.lockUserAccount(userId));
		return map;
	}



	/**将用户的钱冻结到冻结账户里面
	 * 默认的
	 *
	 * **/

	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/freeze")
	public @ResponseBody Object freeUserAccount(HttpServletRequest request,
												@RequestParam(value = "user_id") long userId,
												@RequestParam(value = "amount") BigDecimal amount,
												@RequestParam(value = "add_or_sub",  required=false, defaultValue = "0") String addorsub,
												@RequestParam(value = "order_code",  required=false) String ordercode
	){
		Map<String,Object> map = new HashMap<String,Object>();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		try {
			map.put(CommonConstants.RESULT, userBalBusiness.freezeUserAccount(userAccount, amount, addorsub, ordercode));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;


	}



	/**将用户的分润提现到用户的余额中间去*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/rebate/update")
	public @ResponseBody Object updateUserRebateAccount(HttpServletRequest request,
														@RequestParam(value = "user_id") long userId,
														@RequestParam(value = "amount",  defaultValue = "0",  required=false) BigDecimal amount,
														@RequestParam(value = "addorsub",  defaultValue = "0",  required=false) String addorsub,
														@RequestParam(value = "order_code", required=false) String ordercode
	){
		Map map = new HashMap();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.updateUserRebateAccount(userAccount, amount,  ordercode));
		return map;


	}


	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/rebate/unfreeze")
	public @ResponseBody Object unfreezeUserbateAccount(HttpServletRequest request,
														@RequestParam(value = "user_id") long userId,
														@RequestParam(value = "amount") BigDecimal amount,
														@RequestParam(value = "add_or_sub",  required=false, defaultValue = "0") String addorsub,
														@RequestParam(value = "order_code",  required=false) String ordercode
	){
		Map map = new HashMap();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		try {
			map.put(CommonConstants.RESULT, userBalBusiness.freezeUserRebateAccount(userAccount, amount, addorsub, ordercode));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}



	/**分润提现, 如果满足需求先将钱直接冻结到帐户里面*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/rebate/freeze")
	public @ResponseBody Object freezeAccountRebateBalance(HttpServletRequest request,
														   @RequestParam(value = "user_id") long userId,
														   @RequestParam(value = "realamount") String realamount,
														   @RequestParam(value = "order_code") String ordercode
	){

		UserAccount userAcct = userBalBusiness.rebateFreezeAccount(userId, new BigDecimal(realamount),  ordercode);
		Map map = new HashMap();

		/**提现失败 */
		if(userAcct != null){

			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, userAcct);

		}else{

			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "余额不足");

		}



		return map;


	}


	/**提现请求, 如果满足需求先把钱冻结到账户里面**/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/withdraw/freeze")
	public @ResponseBody Object freezeAccountBalance(HttpServletRequest request,
													 @RequestParam(value = "user_id") long userId,
													 @RequestParam(value = "realamount") String realamount,
													 @RequestParam(value = "order_code") String ordercode
	){

		UserAccount userAcct = userBalBusiness.withdrawFreeAccount(userId, new BigDecimal(realamount),  ordercode);
		Map map = new HashMap();

		/**提现失败 */
		if(userAcct != null){

			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, userAcct);

		}else{

			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "余额不足");

		}



		return map;

	}



	/**更新用户的账户信息 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/update")
	public @ResponseBody Object updateUserAccount(HttpServletRequest request,
												  @RequestParam(value = "user_id") long userId,
												  @RequestParam(value = "amount",  defaultValue = "0",  required=false) BigDecimal amount,
												  @RequestParam(value = "addorsub",  defaultValue = "0",  required=false) String addorsub,
												  @RequestParam(value = "order_code", required=false) String ordercode
	){
		Map<String,Object> map = new HashMap<String,Object>();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		try {
			map.put(CommonConstants.RESULT, userBalBusiness.updateUserAccount(userAccount, amount,  addorsub, ordercode));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(addorsub.equals("0")){
			// TODO: 推送消息
		}
		return map;


	}


	/**查询交易变更历史*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/balance/query/{token}")
	public @ResponseBody Object pageBalanceQuery(HttpServletRequest request,
												 @PathVariable("token") String token,
												 @RequestParam(value = "page", defaultValue = "0", required = false) int page,
												 @RequestParam(value = "size", defaultValue = "20", required = false) int size,
												 @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
												 @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty
	){

		Map map = new HashMap();
		long userId;
		try{
			userId = TokenUtil.getUserId(token);
		}catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		Pageable pageable = new PageRequest(page, size, new Sort(direction,sortProperty));
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.queryUserBalHistoryByUserid(userId, pageable));
		return map;
	}
	/**查询交易收益*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/balance/profit/{token}")
	public @ResponseBody Object pageBalanceQuery(HttpServletRequest request,
												 @PathVariable("token") String token
	){
		Map<String, Object> map = new HashMap<String, Object>();
		long userId;
		try{
			userId = TokenUtil.getUserId(token);
		}catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.findSumUserBalByUserId(userId));

		return map;
	}

	/**
	 * 查询账户余额
	 * @param token
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/user/balance/getbalance/{token}")
	public @ResponseBody Object getBalance(@PathVariable(value = "token") String token) {
		long userId = 0l;
		Map<String, Object> res = new HashMap<>();
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			LOG.error("tiken无效！");
			return CommonsUtil.returnError("token无效！");
		}
		try {
			/* 1、获取用户账户信息 */
			UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);
			LOG.info("获取用户账户信息userId = " + userId + "，userAccount = " + userAccount.toString());

			/* 2、获取今日收益的分润 */
			URI uri = util.getServiceUrl("paymentchannel", "error error url request!");
			String url = uri.toString() + "/v1.0/paymentchannel/freeQuickPay/getTodayIncome";

			MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>();
			requestEntity.add("userId", userId);

			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);

			LOG.info("获取分润的今日收益/v1.0/paymentchannel/freeQuickPay/getTodayIncome userId = " + userId + ", result = " + result);

            JSONObject jsonObject = JSONObject.fromObject(result);
            if (!CommonConstants.SUCCESS.equals(jsonObject.getString("resp_code"))) {
                return CommonsUtil.returnError("获取今日收益失败！");
            }

            String todayInComeStr = jsonObject.get("result").toString();
			BigDecimal todayInCome = new BigDecimal(todayInComeStr).setScale(2, BigDecimal.ROUND_DOWN);
			LOG.info("todayInCome = " + todayInCome);

            userAccount.setTodayInCome(todayInCome);

			/* 3、获取通道列表 */
			//List<Channel> channelList = userBalBusiness.getChannelList(userId, 2, -1);
			//LOG.info("获取通道列表channelList = " + channelList.toString());
			Map<String, Object> defaultChannel = getChannel(userId, 2, -1);
			res.putAll(defaultChannel);
			res.put("userAccount", userAccount);

			LOG.info("查询账户余额接口/v1.0/user/balance/getbalance/{token}返回res = " + res.toString());

			//jsonObject = JSONObject.fromObject(res);

			res.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			res.put(CommonConstants.RESP_MESSAGE, "用户账户信息获取成功！");
			jsonObject = JSONObject.fromObject(res);

			LOG.info("json = " + jsonObject);
			return jsonObject;

//			LOG.info("res = " + res);
//			return res;
		} catch (Exception e) {
			LOG.error("获取用户账户信息异常/v1.0/user/balance/getbalance/{token} userId = " + userId);
			e.printStackTrace();
			return CommonsUtil.returnError("服务器异常！");
		}
	}

	/**
	 * 获取渠道
	 * @param userId
	 * @param payType
	 * @param channelId
	 * @return
	 */
	public Map<String, Object> getChannel (long userId, long payType, long channelId) {
		Map<String, Object> res = new HashMap<>();
		List<Channel> channelList = userBalBusiness.getChannelList(userId, payType, channelId,"","");
		LOG.info("获取通道列表channelList = " + channelList.toString());
		if (channelList == null && channelList.size() == 0) {
			return CommonsUtil.returnError("获取通道失败！");
		}
		for (Channel channel : channelList) {
			String channelTag = channel.getChannelTag();
			if ("CHANPAYNEWCARD_0101".equals(channelTag)) {
				channel.setRate(BigDecimal.ZERO);
				res.put("defaultChannel", channel);
			}
		}
		return res;
	}

	/**
	 * 余额提现时更新用户账户信息
	 * @param userId
	 * @param amount 提现金额
	 * @param actualAmount 实际提现金额
	 * @param balance 余额 = 初始余额 - 提现金额
	 * @param bankCard 银行卡
	 * @param orderCode 提现订单
	 * @param addorsub 0加1减（0充值，1提现）
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount/updateAccount")
	public @ResponseBody Object updateAccount(@RequestParam(value = "userId") long userId,
											  @RequestParam(value = "amount") BigDecimal amount,
											  @RequestParam(value = "actualAmount") BigDecimal actualAmount,
											  @RequestParam(value = "balance") BigDecimal balance,
											  @RequestParam(value = "bankCard") String bankCard,
											  @RequestParam(value = "orderCode") String orderCode,
											  @RequestParam(value = "addorsub") String addorsub) {
		UserAccount userAccount = userBalBusiness.updateAccount(bankCard, userId, amount, actualAmount, orderCode, balance, addorsub);
		return CommonsUtil.returnSuccess(userAccount, "更新成功！");
	}

	/**
	 * 更新分润余额
	 * @param userAccount
	 * @param amount
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount/addAccount")
	public @ResponseBody Object addAccount(UserAccount userAccount,BigDecimal amount){
		try {
			userBalBusiness.addUserAccount(userAccount,amount);
			return CommonsUtil.returnSuccess("");
		}catch (Exception e){
			LOG.error("同步数据到分润表异常=====" + e.getMessage());
			return CommonsUtil.returnError("同步数据到分润表失败！" + e.getMessage());
		}

	}

	/**
	 * 分润提现到余额
	 * @param userId
	 * @param rebateAmount 分润提现金额
	 * @param rebateBalance 提现前分润余额
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount/rebateWithdraw")
	public @ResponseBody Object rebateWithdraw(HttpServletRequest request,
											   @RequestParam(value = "userId") long userId,
											   @RequestParam(value = "rebateAmount") BigDecimal rebateAmount,
											   @RequestParam(value = "rebateBalance") BigDecimal rebateBalance) {
		LOG.info("分润提现到余额/v1.0/user/userAccount/rebateWithdraw userId = " + userId + ", rebateAmount = " + rebateAmount + ", rebateBalance = " + rebateBalance);
		try {
			if (rebateAmount.compareTo(new BigDecimal("0.00")) == 0) {
				return CommonsUtil.returnError("请输入提现金额！");
			}
			if (rebateAmount.compareTo(new BigDecimal("0.00")) == 0) {
				return CommonsUtil.returnError("余额不足，无法提现！");
			}
			if (rebateAmount.compareTo(rebateBalance) > 0) {
				return CommonsUtil.returnError("余额不足，无法提现！");
			}
			if (rebateAmount.compareTo(new BigDecimal("100.00")) < 0) {
				return CommonsUtil.returnError("每笔提现金额不能低于100.00！");
			}
			if (rebateAmount.compareTo(new BigDecimal("20000.00")) > 0) {
				return CommonsUtil.returnError("每笔提现金额不能高于20000.00！");
			}

			UserAccount userAccount = userBalBusiness.rebateWithdraw(userId, rebateAmount, rebateBalance);
			if (userAccount == null) {
				return CommonsUtil.returnError("提现失败！");
			}
			LOG.info("分润提现成功v1.0/user/userAccount/rebateWithdraw userAccount = " + userAccount.toString());
			return CommonsUtil.returnSuccess(userAccount, "提现成功！");
		} catch (Exception e) {
			LOG.error("userId = " + userId + "，用户分润提现异常！");
			if ("未获取用户账户信息！".equals(e.getMessage()) || "提现失败！".equals(e.getMessage())) {
				return CommonsUtil.returnError(e.getMessage());
			}
			return CommonsUtil.returnError("提现失败，请稍后重试！");
		}
	}

	/**
	 * 查询 '我的-账单-提现' 记录
	 * @param token
	 * @param page
	 * @param size
	 * @param direction
	 * @param sortProperty
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount/queryAccountHistory/{token}")
	public @ResponseBody Object queryAccountHistory(@PathVariable(value = "token") String token,
													@RequestParam(value = "page", defaultValue = "0", required = false) int page,
													@RequestParam(value = "size", defaultValue = "20", required = false) int size,
													@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
													@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效");
		}
		try {
			Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
			Page<UserBalanceHistory> userBalanceHistoryPage = userBalBusiness.queryAccountHistory(userId, pageable);
			return CommonsUtil.returnSuccess(userBalanceHistoryPage, "提现记录查询成功");
		} catch (Exception e) {
			return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}

	/**
	 * 查询 ‘我的-账单-分润’ 记录
	 * @param token
	 * @param page
	 * @param size
	 * @param direction
	 * @param sortProperty
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount/queryRebatePage/{token}")
	public @ResponseBody Object queryRebatePage(@PathVariable(value = "token") String token,
												@RequestParam(value = "page", defaultValue = "0", required = false) int page,
												@RequestParam(value = "size", defaultValue = "20", required = false) int size,
												@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
												@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		long userId = 0;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效！");
		}
		try {
			Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
			Page<UserRebateAccountFreezeHistory> rebatePage = userBalBusiness.queryRebatePage(userId, pageable);
			return CommonsUtil.returnSuccess(rebatePage, "分润记录查询成功！");
		} catch (Exception e) {
			return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}

	/**
	 * 提现失败，退款
	 * @param userId
	 * @param orderCode
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount/refundBalannce")
	public @ResponseBody Object refundBalannce(@RequestParam(value = "userId") long userId,
											   @RequestParam(value = "orderCode") String orderCode) {
	    try {
		    UserAccount userAccount = userBalBusiness.refundBalannce(userId, orderCode);
	        return CommonsUtil.returnSuccess(userAccount, "退款成功！");
        } catch (Exception e) {
	        return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
	}


	/**
	 * 查询余额明细
	 * @param token
	 * @param page
	 * @param size
	 * @param direction
	 * @param sortProperty
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount/queryBalanceDetails/{token}")
	public @ResponseBody Object queryBalanceDetails(@PathVariable(value = "token") String token,
													@RequestParam(value = "page",defaultValue = "0", required = false) int page,
													@RequestParam(value = "size", defaultValue = "20", required = false) int size,
													@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
													@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效！");
		}
		try {
			Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
			Page<PaymentProfit> paymentProfitPage = paymentProfitBusiness.queryBalanceDetails(userId, pageable);
			return CommonsUtil.returnSuccess(paymentProfitPage, "分页查询余额明细成功！");
		} catch (Exception e) {
			return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userAccount//{token}")
	public @ResponseBody Object saveAccount(@PathVariable(value = "token") String token,
													@RequestParam(value = "page",defaultValue = "0", required = false) int page,
													@RequestParam(value = "size", defaultValue = "20", required = false) int size,
													@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
													@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效！");
		}
		try {
			Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
			Page<PaymentProfit> paymentProfitPage = paymentProfitBusiness.queryBalanceDetails(userId, pageable);
			return CommonsUtil.returnSuccess(paymentProfitPage, "分页查询余额明细成功！");
		} catch (Exception e) {
			return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}
}
